package cn.bytecollege.filter;

import cn.bytecollege.constant.Resource;
import cn.bytecollege.entity.RoomCategory;
import cn.bytecollege.service.RoomCategoryService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Mr.H
 */
@WebFilter(filterName = "RoomCategoryAddFilter",servletNames = {"RoomCategoryAddController","RoomCategoryUpdateController"})
public class RoomCategoryAddFilter implements Filter {
    private RoomCategoryService roomCategoryService=new RoomCategoryService();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String msg=null;
        String method=request.getMethod();
        //  接收参数
        String name=request.getParameter("name");
        if (method.equalsIgnoreCase("post")){
            if (name==null||name.equals("")){
                msg="分类名不能为空，请输入！";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION+"/roomCategoryAdd.jsp").forward(servletRequest, servletResponse);
                return;
            }
            Pattern p=Pattern.compile("^[\\u4e00-\\u9fa5]{0,}$");
            Matcher m=p.matcher(name);
            if (!m.matches()){
                msg="分类名只能是汉字，请输入！";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION+"/roomCategoryAdd.jsp").forward(servletRequest, servletResponse);
                return;
            }
            //代码执行到这说明分类名是汉字不为空
            RoomCategory roomCategory=roomCategoryService.findRoomCategoryByCategoryName(name);
            if (roomCategory!=null){
                msg="该分类已存在";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION+"/roomCategoryUpdate.jsp").forward(servletRequest, servletResponse);
                return;
            }
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
